# -*- conding:UTF-8 -*-

'''
@ Project: P8 flask_progect
@ File: learnInfo.py
@ Author: 罗婷
@ Date：2022/6/27 16:09

'''



import json
# TODO 七牛云上传头像
from qiniu import Auth
from flask import Blueprint, jsonify
from flask_restful import Api, Resource, reqparse, marshal

from common.jwt.check_token import token_check
from common.model_fields.courses import *
from common.model_fields.users import users_fields
from common.models.course import *
from common.models.users import Users

learn_bp = Blueprint('learn_bp', __name__,)

api = Api(learn_bp)

# 获取学习进度
class LearnInfo(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('cid')
        args = parser.parse_args()
        token = args['token']
        cid = args['cid']
        # print('@@@@@@@@@@@@@@@@@@@获取学习进度^^^^^^^^', 'cid课程id', cid, 'token', token)
        # res.data 章节 嵌套小节

        course = Course.query.filter_by(id=cid).first()   # 课程详情
        chapters = course.chapter                         # 章节详情
        # chapters_ser = json.loads(json.dumps(marshal(chapters, chapter_fields)))
        chapters_ser = marshal(chapters, chapter_fields)
        # chapters_data = []                                # 章节详情列表
        # for i in chapters:
        #     # 根据字段获取小节信息
        #     section = i.sections
        #     # 序列化所有小节字段
        #     section_data = json.loads(json.dumps(marshal(section, section_fields)))
        #     # 序列化 每一个遍历的 章节字段
        #     chapters_ser = json.loads(json.dumps(marshal(i, chapter_fields)))
        #     # 将所有小节放入 当前遍历的章节
        #     chapters_ser['section'] = section_data
        #     # 将添加了小节信息的章节放入章节列表
        #     chapters_data.append(chapters_ser)

        return jsonify(message='章节信息获取成功', code=200, data=chapters_ser)

# 改变课程关注状态
class CollectCoures(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('course_id')
        args = parser.parse_args()
        cid = args['course_id']
        # print('@@@@@@@@@@@@@@@@@@@ 改变课程关注状态^^^^^^^^', 'cid课程id', cid)
        course = Course.query.filter_by(id=cid).first()
        collect = course.is_collect
        if collect:  # 关注  ====  取消关注
            Course.query.filter_by(id=cid).update({'is_collect': False})
            db.session.commit()
            return jsonify(message='取消关注成功', code=200)
        else:  # 取消关注   ====  关注
            Course.query.filter_by(id=cid).update({'is_collect': True})
            db.session.commit()
            return jsonify(message='关注成功', code=200)

# 点赞评论
class Zan(Resource):
        # is_favorite 是否点赞
        #         com_id: this.comment.id,
        #         receive_id: this.comment.user,
        #         token: localStorage.getItem("token"),
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('com_id')   # 被点赞的id
        parser.add_argument('receive_id')
        parser.add_argument('token')
        args = parser.parse_args()
        com_id = args['com_id']
        uid = args['receive_id']
        token = args['token']
        # print('@@@@@@@@@@@@@@@@@@@ 点赞^^^^^^^^', 'com_id', com_id, 'uid', uid, 'token', token)
        comms = Comments.query.filter_by(id=com_id, user=uid).first()
        comms_data = json.loads(json.dumps(marshal(comms, comment_fields)))
        print('comms点赞:', comms_data)
        add_zan_num = comms.zan_num+1
        rec_zan_num = comms.zan_num-1
        print('点赞数量', rec_zan_num)
        if comms.is_favorite:  # 点赞了  取消点赞
            Comments.query.filter_by(id=com_id, user=uid).update({'is_favorite': False, 'zan_num': rec_zan_num})
            db.session.commit()
            comms = Comments.query.filter_by(id=com_id, user=uid).first()
            comms_data = marshal(comms, comment_fields)
            return jsonify(message='取消点赞成功', code=200, data=comms_data)
        else:  # 没点赞  === 点赞
            Comments.query.filter_by(id=com_id, user=uid).update({'is_favorite': True, 'zan_num': add_zan_num})
            db.session.commit()
            comms = Comments.query.filter_by(id=com_id, user=uid).first()
            comms_data = marshal(comms, comment_fields)
            return jsonify(message='点赞成功', code=200, data=comms_data)


access_key = '74F2GCXwNJ2c9fgiD3ufHUUDXUrSdgNXW6kmIrXY'
secret_key = 'LqiDv9FZT8oLhDMHrLWwR-HP1vOoEguyQWUQlmNz'
# 获取七牛云token  res.token
class QiniuToken(Resource):
    def get(self):
        q = Auth(access_key, secret_key)
        bucket = 'p7lotk'
        token = q.upload_token(bucket)
        print('获取七牛云token--------', token)
        return jsonify(message='成功', code=200, token=token)

# 修改用户信息
class ChangeUserInfo(Resource):
    #         token: localStorage.getItem("token"),
    #         username: this.username,
    #         occupation: this.occupation,
    #         school: this.school,
    #         img: this.imgkey,
    def post(self):
        parser = reqparse.RequestParser()
        argss = ['username', 'token', 'occupation', 'school', 'img']
        for i in argss:
            parser.add_argument(i)
        args = parser.parse_args()
        account = args['username']
        token = args['token']
        occupation = args['occupation']
        school = args['school']
        profile_photo = args['img']
        print('修改用户信息', 'account', account, 'token', token,  'occupation', occupation,  'school', school, 'profile_photo', profile_photo)
        # 校验token
        payload = token_check(token)
        print('校验出的payloa@@@@@@@', payload)
        # {'uid': 1, 'account': 'admin1', 'exp': 1656336094}
        if payload:
            Users.query.filter_by(uid=payload['uid']).update({
                'account': account, 'occupation': occupation,
                'school': school, 'profile_photo': profile_photo})
            db.session.commit()
            return jsonify(message='修改成功', code=200)
        else:
            return jsonify(message='请登录', code=400)



# 学习进度信息
api.add_resource(LearnInfo, '/learninfo/')
# 收藏状态改变
api.add_resource(CollectCoures, '/collect/')
# 点赞评论
api.add_resource(Zan, '/favorite_comment/')
# 获取七牛云token
api.add_resource(QiniuToken, '/uptoken/')
# 修改用户信息
api.add_resource(ChangeUserInfo, '/user_info/')

